﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using OpenSearch;

namespace FederatedSearchSL.Web
{
    public partial class GetOpenSearchDef : System.Web.UI.Page
    {

        protected void Page_Load(object sender, EventArgs e)
        {
            string action = Request["action"];
            if (!string.IsNullOrEmpty(action))
            {
                OpenSearchDescription osdx = null;
                if( action == "bing" )
                    osdx = CreateBingOSDX(Decode(Request["sn"]), UrlDecode(Request["url"]));
                else if( action == "osdx" )
                    osdx = CreateOSDX();

                if (osdx != null) SendOSDX(osdx);
                else throw new ArgumentException("Invalid action specified");
            }
        }

        private string Decode(string src)
        {
            return HttpUtility.HtmlDecode(src);
        }

        private string UrlDecode(string src)
        {
            string url = HttpUtility.HtmlDecode(src);

            // URL's must begin with protocol identifier
            if (!url.StartsWith("http")) url = "http://" + url;

            return url;
        }
        
        public void SendOSDX(OpenSearchDescription osdx)
        {
            if (string.IsNullOrEmpty(osdx.ShortName)) return;

            string xml = osdx.SerializeToXml();

            Response.Clear();
            Response.ContentType = "application/opensearchdescription+xml";
            Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(osdx.ShortName) + ".osdx");
            Response.Write(xml);
            Response.Flush();
            Response.End();
        }

        /// <summary>
        /// Creates the OSDX file using Bing as the search provider with
        /// scoped results for the URL.
        /// </summary>
        private OpenSearchDescription CreateBingOSDX(string shortName, string url)
        {
            OpenSearchDescription osdx = OpenSearchDescription.FromGenericSiteUrl(UrlDecode(url));
            osdx.ShortName = shortName;
            return osdx;
        }

        /// <summary>
        /// Creates the OSDX file from querystring parameters.  Must have short name (sn) set.
        /// </summary>
        private OpenSearchDescription CreateOSDX()
        {
            OpenSearchDescription osdx = new OpenSearchDescription();
            osdx.ShortName = Decode(Request["sn"]);
            osdx.Description = Decode(Request["d"]);

            // TODO: Consider encoded/unencoded URL's here...
            if (!string.IsNullOrEmpty(Request["atom"]))
                osdx.Templates.Add(new OsdxTemplate { Format = OsdxFormat.ATOM, TemplateUrl = UrlDecode( Request["atom"]) });

            if (!string.IsNullOrEmpty(Request["html"]))
                osdx.Templates.Add(new OsdxTemplate { Format = OsdxFormat.HTML, TemplateUrl = UrlDecode(Request["html"]) });

            if (!string.IsNullOrEmpty(Request["rss"]))
                osdx.Templates.Add(new OsdxTemplate { Format = OsdxFormat.RSS, TemplateUrl = UrlDecode(Request["rss"]) });

            return osdx;
        }
    }
}
/* Example RSS feeds for searching
 * http://news.google.com/news?q={searchTerms}&output=rss
 * http://news.search.yahoo.com/news/rss?p={searchTerms}&ei=UTF-8&eo=UTF-8
 * http://shop.ebay.com/i.html?_nkw={searchTerms}&_rss=1
 * http://api.flickr.com/services/feeds/photos_public.gne?tags={searchTerms}&format=rss_200
*/